from flask import Flask, request
import subprocess
app = Flask(__name__)


path_to_rank_table_file = "E:\\lqy_mindspore_202310\\file.json"

#sh脚本所在的绝对路径
script_path = "E:\\lqy_mindspore_202310\\mindformers\\research\\run_singlenode.sh"

#自己写的那个文件
pipeline_file = "C:\\Users\\Administrator\\PycharmProjects\\flaskProject\\pipeline_file.py"

@app.route('/get_keyword', methods=['GET'])
def get_keyword():
    #获取参数
    keyword = request.args.get('keyword')

    #拼接第一个参数 例子：" python xxx/pipeline_file.py #{keyword}" ,作用是将接口接受到的keyword参数，传递给模型。
    arg1 = "\"python " + pipeline_file + " " + keyword + "\""

    #subprocess.run第一个参数用来拼接要执行的命令，例如["sh", script_path, arg1, path_to_rank_table_file, [0, 2], 2]，
    #假设keyword是“你是谁”,那么上面的这个参数最终执行的是
    #sh "python xxx/pipelin_file.py 你是谁" E:\\lqy_mindspore_202310\\file.json [0, 2], 2
    try:

        #正式环境用这个
        # result = subprocess.run(["sh", script_path, arg1, path_to_rank_table_file, "[0, 2]", 2],
        #                         text=True,
        #                         capture_output=True,encoding="utf-8")

        #底下这个是测试用的
        result = subprocess.run(["python", pipeline_file, keyword],
                                text=True,
                                capture_output=True,
                                encoding="utf-8")
        if result.returncode == 0:
            return result.stdout
        else:
            print("脚本执行失败，错误信息为:")
            return (result.stderr)
    except Exception as e:
        return "脚本执行错误" + e


if __name__ == '__main__':
    app.run(debug=True, port=9001)
